<script setup>
import ip from '@/utils/baseURL.js';
import { ref, reactive, onMounted, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Search } from '@element-plus/icons-vue';
import axios from 'axios';
import debounce from 'lodash/debounce';

// 获取当前用户的 session
const session = localStorage.getItem('session');

// API基础URL
const apiBaseUrl = ip + '/inter';

// 表格数据和加载状态
const paperList = ref([]);
const tableLoading = ref(false);

// 搜索关键词
const searchKeyword = ref('');

// 论文类型列表 (根据数据中包含的类型动态生成)
const paperTypes = ref([
  'SCI一区期刊', 
  'SCI二区期刊', 
  'SCI三区期刊', 
  'SCI四区期刊', 
  'EI期刊', 
  '国内核心期刊', 
  '会议论文',
  '其他'
]);

// 年份筛选
const selectedYear = ref('');
const selectedType = ref('');
const availableYears = ref([]);
const allPapers = ref([]); // 存储所有论文数据，用于前端筛选

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 对话框控制
const dialogVisible = ref(false);
const isEditing = ref(false);
const submitting = ref(false);

// 表单引用和数据
const paperFormRef = ref(null);
const paperForm = reactive({
  id: null,
  achievementName: '',
  type: '',
  dateString: '', // 用于日期选择器
  date: null, // 用于存储后端期望的日期数组格式
  impactFactor: '',
  members: '',
  digest: '',
});

// 表单验证规则
const formRules = {
  achievementName: [
    { required: true, message: '请输入论文标题', trigger: 'blur' },
    { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择论文类型', trigger: 'change' }
  ],
  dateString: [
    { required: true, message: '请选择发表日期', trigger: 'change' }
  ],
  impactFactor: [
    { required: true, message: '请输入影响因子', trigger: 'blur' }
  ],
  members: [
    { required: true, message: '请输入作者', trigger: 'blur' }
  ]
};

// 获取论文类型标签样式
const getPaperTypeTag = (type) => {
  const typeMap = {
    'SCI一区期刊': 'danger',
    'SCI二区期刊': 'warning',
    'SCI三区期刊': 'success',
    'SCI四区期刊': 'info',
    'EI期刊': 'primary',
    '国内核心期刊': 'success',
    '会议论文': 'info'
  };
  return typeMap[type] || 'info';
};

// 格式化日期数组为显示字符串
const formatDateDisplay = (dateArray) => {
  if (!dateArray || !Array.isArray(dateArray) || dateArray.length < 3) {
    return '未知日期';
  }
  const [year, month, day] = dateArray;
  // 补充前导零
  const formattedMonth = month.toString().padStart(2, '0');
  const formattedDay = day.toString().padStart(2, '0');
  return `${year}-${formattedMonth}-${formattedDay}`;
};

// 处理年份变化
const handleYearChange = () => {
  filterPapers();
};

// 处理类型变化
const handleTypeChange = () => {
  filterPapers();
};

// 根据筛选条件过滤论文
const filterPapers = () => {
  let filtered = [...allPapers.value];
  
  // 应用年份筛选
  if (selectedYear.value) {
    filtered = filtered.filter(paper => {
      if (paper.date && Array.isArray(paper.date) && paper.date.length > 0) {
        return paper.date[0] === selectedYear.value;
      }
      return false;
    });
  }
  
  // 应用类型筛选
  if (selectedType.value) {
    filtered = filtered.filter(paper => paper.type === selectedType.value);
  }
  
  paperList.value = filtered;
  pagination.total = filtered.length;
};

// 加载论文列表数据
const loadPaperList = async () => {
  tableLoading.value = true;
  try {
    // 构建查询参数
    const params = {
      page: pagination.currentPage,
      pageSize: pagination.pageSize,
      keyword: searchKeyword.value || undefined
    };
    
    const response = await axios.get(`${apiBaseUrl}/achievement/getAchievement`, { params });
    
    if (response.data.code === 200) {
      const records = response.data.data.records || [];
      allPapers.value = records;
      
      // 提取所有可用的年份
      const years = new Set();
      records.forEach(paper => {
        if (paper.date && Array.isArray(paper.date) && paper.date.length > 0) {
          years.add(paper.date[0]);
        }
      });
      availableYears.value = Array.from(years).sort((a, b) => b - a); // 降序排列
      
      // 提取所有可用的论文类型
      const types = new Set();
      records.forEach(paper => {
        if (paper.type) {
          types.add(paper.type);
        }
      });
      if (types.size > 0) {
        paperTypes.value = Array.from(types);
      }
      
      // 应用筛选
      filterPapers();
      
      pagination.total = response.data.data.count || 0;
    } else {
      ElMessage.error(response.data.message || '获取论文信息失败');
    }
  } catch (error) {
    console.error('加载论文信息错误:', error);
    ElMessage.error('网络错误，请稍后重试');
  } finally {
    tableLoading.value = false;
  }
};

// 搜索防抖
const debounceSearch = debounce(() => {
  pagination.currentPage = 1;
  loadPaperList();
}, 300);

// 处理页面大小变化
const handleSizeChange = (size) => {
  pagination.pageSize = size;
  loadPaperList();
};

// 处理页码变化
const handleCurrentChange = (page) => {
  pagination.currentPage = page;
  loadPaperList();
};

// 添加论文信息
const handleAddPaper = () => {
  isEditing.value = false;
  resetForm();
  dialogVisible.value = true;
};

// 编辑论文信息
const handleEditPaper = (row) => {
  isEditing.value = true;
  resetForm();
  
  // 复制数据到表单
  paperForm.id = row.id;
  paperForm.achievementName = row.achievementName;
  paperForm.type = row.type;
  paperForm.dateString = formatDateDisplay(row.date);
  paperForm.impactFactor = row.impactFactor;
  paperForm.members = row.members;
  paperForm.digest = row.digest;
  
  dialogVisible.value = true;
};

// 删除论文信息
const handleDeletePaper = (row) => {
  ElMessageBox.confirm(`确定要删除论文"${row.achievementName}"吗？此操作不可恢复！`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      // 使用正确的删除API接口
      const response = await axios.delete(`${apiBaseUrl}/adminAchievement/delete/?id=${row.id}`,{headers: {
        'Session': `${session}`, // 传递 session
      },
      });
      
      if (response.data.code === 200) {
        ElMessage.success('删除成功');
        loadPaperList();
      } else {
        ElMessage.error(response.data.message || '删除失败');
      }
    } catch (error) {
      console.error('删除论文信息错误:', error);
      ElMessage.error('网络错误，请稍后重试');
    }
  }).catch(() => {});
};

// 重置表单
const resetForm = () => {
  if (paperFormRef.value) {
    paperFormRef.value.resetFields();
  }
  paperForm.id = null;
  paperForm.achievementName = '';
  paperForm.type = '';
  paperForm.dateString = '';
  paperForm.impactFactor = '';
  paperForm.members = '';
  paperForm.digest = '';
};

// 将日期字符串解析为数组
const parseDateString = (dateString) => {
  if (!dateString) return null;
  const [year, month, day] = dateString.split('-').map(num => parseInt(num, 10));
  return [year, month, day];
};

// 提交论文表单
const submitPaperForm = () => {
  paperFormRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true;
      try {
        // 转换成后端期望的格式
        const formData = {
          // 有id就是修改，没有就是新增
          ...(paperForm.id ? { id: paperForm.id } : {}),
          achievementName: paperForm.achievementName,
          type: paperForm.type,
          date: parseDateString(paperForm.dateString),
          impactFactor: paperForm.impactFactor,
          members: paperForm.members,
          digest: paperForm.digest
        };
        
        // 使用正确的接口URL
        const url = `${apiBaseUrl}/adminAchievement/saveOrUpdateInfo`;
       
          
        const response = await axios.post(url, formData,{headers: {
          'Session': `${session}`, // 传递 session
        },
        });
        
        if (response.data.code === 200) {
          ElMessage.success(isEditing.value ? '更新成功' : '添加成功');
          dialogVisible.value = false;
          loadPaperList();
        } else {
          ElMessage.error(response.data.message || (isEditing.value ? '更新失败' : '添加失败'));
        }
      } catch (error) {
        console.error('提交论文信息错误:', error);
        ElMessage.error('网络错误，请稍后重试');
      } finally {
        submitting.value = false;
      }
    }
  });
};

// 页面初始化时加载数据
onMounted(() => {
  loadPaperList();
});
</script>

<template>
  <div class="paper-container">
    <div class="page-header">
      <h1>论文(成果)管理</h1>
    </div>

    <!-- 功能按钮区域 -->
    <div class="actions-panel">
      <el-button type="primary" @click="handleAddPaper">添加论文成果</el-button>
      <div class="filter-panel">
        <el-select
          v-model="selectedYear"
          placeholder="选择年份"
          clearable
          @change="handleYearChange"
          class="year-select"
        >
          <el-option
            v-for="year in availableYears"
            :key="year"
            :label="year + '年'"
            :value="year"
          />
        </el-select>
        <el-select
          v-model="selectedType"
          placeholder="论文类型"
          clearable
          @change="handleTypeChange"
          class="type-select"
        >
          <el-option
            v-for="type in paperTypes"
            :key="type"
            :label="type"
            :value="type"
          />
        </el-select>
        <div class="search-panel">
          <el-input 
            v-model="searchKeyword" 
            placeholder="搜索论文标题或作者" 
            clearable 
            @clear="loadPaperList" 
            @input="debounceSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>
      </div>
    </div>

    <!-- 论文信息表格 -->
    <el-table 
      :data="paperList" 
      style="width: 100%" 
      border 
      v-loading="tableLoading"
    >
      <el-table-column label="序号" type="index" width="60" align="center" />
      <el-table-column prop="achievementName" label="论文标题" min-width="220" />
      <el-table-column prop="type" label="论文类型" width="120">
        <template #default="scope">
          <el-tag :type="getPaperTypeTag(scope.row.type)">
            {{ scope.row.type }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="date" label="发表日期" width="120" sortable>
        <template #default="scope">
          {{ formatDateDisplay(scope.row.date) }}
        </template>
      </el-table-column>
      <el-table-column prop="impactFactor" label="影响因子" width="100" />
      <el-table-column prop="members" label="作者" min-width="140" />
      <el-table-column prop="digest" label="摘要" min-width="240">
        <template #default="scope">
          <div class="digest-cell">
            {{ scope.row.digest || '暂无摘要' }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180" fixed="right">
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleEditPaper(scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDeletePaper(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页控件 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加/编辑论文信息对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEditing ? '编辑论文信息' : '添加论文信息'"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form :model="paperForm" label-width="100px" :rules="formRules" ref="paperFormRef">
        <el-form-item label="论文标题" prop="achievementName">
          <el-input v-model="paperForm.achievementName" placeholder="请输入论文标题" />
        </el-form-item>
        <el-form-item label="论文类型" prop="type">
          <el-input v-model="paperForm.type" placeholder="请输入论文类型，如：SCI一区期刊、会议论文等" />
        </el-form-item>
        <el-form-item label="发表日期" prop="date">
          <el-date-picker 
            v-model="paperForm.dateString" 
            type="date" 
            placeholder="选择发表日期"
            style="width: 100%"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="影响因子" prop="impactFactor">
          <el-input v-model="paperForm.impactFactor" placeholder="请输入影响因子" />
        </el-form-item>
        <el-form-item label="作者" prop="members">
          <el-input v-model="paperForm.members" placeholder="请输入作者，多个作者用逗号分隔" />
        </el-form-item>
        <el-form-item label="论文摘要" prop="digest">
          <el-input 
            v-model="paperForm.digest"
            type="textarea"
            :rows="4"
            placeholder="请输入论文摘要内容"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitPaperForm" :loading="submitting">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>



<style lang="scss" scoped>
.paper-container {
  padding: 20px;
  
  .page-header {
    margin-bottom: 20px;
    
    h1 {
      font-size: 24px;
      margin: 0;
    }
  }
  
  .actions-panel {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;
    
    .filter-panel {
      display: flex;
      gap: 10px;
      align-items: center;
      
      .year-select, .type-select {
        width: 120px;
      }
      
      .search-panel {
        width: 250px;
      }
    }
  }
  
  .digest-cell {
    max-width: 250px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}

:deep(.el-table) {
  margin-bottom: 20px;
}
</style>